package org.wu.reggie.controller;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.wu.reggie.common.R;
import org.wu.reggie.entity.Employee;
import org.wu.reggie.entity.Page;
import org.wu.reggie.service.EmployeeService;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/employee")
@Slf4j
public class EmployeeController {


    @Autowired
    private EmployeeService employeeService;


    /**
     * 作用：登录
     * @param employee 封装用户名和密码
     * @param session   会话域对象
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpSession session){


        // 查看是否有该用户
        R<Employee> result = employeeService.login(employee);

        // 判断是否登录成功 如果登录成功 则往session中保存记录
        if (result.getCode() == 1){
            // 设置登录成功标记
            session.setAttribute("employee",result.getData().getId());
        }
        return result;
    }

    @PostMapping("/logout")
    public R<String> logout(HttpSession session){
        session.invalidate();//删除session记录
        return R.success("退出成功");
    }

    @PostMapping
    public R<String> save(@RequestBody Employee employee,HttpSession session){

        // 0 判断用户名是否相同 如果相同在里面直接抛异常
        employeeService.checkName(employee);


        // 1 获取当前登录的用户 补全员工的创建者与修改者  MySQLIntegrityConstraintViolationException
        Long empId = (Long)session.getAttribute("employee");
        employee.setCreateUser(empId);
        employee.setUpdateUser(empId);

        // 2 把数据交给service层
        employeeService.save(employee);
        return R.success("保存成功");
    }

    @GetMapping("/page")
    public R<Page<Employee>> page(Integer page,Integer pageSize,String name){
        System.out.println(page);
        System.out.println(pageSize);
        System.out.println(name);

        Page<Employee> pageResult = employeeService.findByPage(page,pageSize,name);

        return R.success(pageResult);
    }

    @PutMapping
    public R<String> update(@RequestBody Employee employee,HttpSession session){

        // 1 获取当前登录用户 修改更新信息
        Long empId = (Long) session.getAttribute("employee");
        employee.setUpdateUser(empId);
        // 2 把信息交给service
        employeeService.update(employee);

        return R.success("修改成功");
    }

    @GetMapping("/{id}")
    public R<Employee> findById(@PathVariable("id") Long id){
        Employee employee = employeeService.findById(id);
        return R.success(employee);
    }
}
